package org.anachronos.jeep.agent.attach;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.management.ManagementFactory;
import java.net.URISyntaxException;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.anachronos.jeep.core.attach.VirtualMachineRemoteControl;

public class AttachServer {
	public static void main(String[] args) throws Exception {
		// TODO: This is needed so that it runs on my computer
		if (!System.getProperties().containsKey("java.rmi.server.hostname")) {
			System.setProperty("java.rmi.server.hostname", "localhost");
		}
		System.setProperty(VirtualMachineRemoteControl.OWN_JVMS_MARKER, 
				VirtualMachineRemoteControl.OWN_JVMS_MARKER);
		final ObjectName objectName = getVirtualMachineControlName();
		
		final VirtualMachineControl virtualMachineControl = new VirtualMachineControl();
		System.out.println(virtualMachineControl.loadJmxAgent());
		System.err.println(System.getProperties());
		
		final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
		if (!platformMBeanServer.isRegistered(objectName)) {
			platformMBeanServer.registerMBean(virtualMachineControl, objectName);
		}
		while(true);
	}

	private static ObjectName getVirtualMachineControlName() throws Exception {
		return new ObjectName(VirtualMachineControl.NAME);
	}

	public static String getJarFile()  {
		String path;
		try {
			path = new File(AttachServer.class.getProtectionDomain().
				getCodeSource().getLocation().toURI()).getPath();
			if (!path.endsWith(".jar")) {
				return getJarFileInTests(path);
			} else {
				return path;
			}
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * When running integration tests the classes aren't stored in a jar.
	 * So we have the find the jar in the target dir.
	 */
	private static String getJarFileInTests(final String path) {
		final File targetDir = new File(path).getParentFile();
		final String[] jarFiles = targetDir.list(new FilenameFilter() {
			@Override
			public boolean accept(File _, final String name) {
				return name.endsWith("jar-with-dependencies.jar");
			}
		});
		if (jarFiles == null || jarFiles.length != 1) {
			throw new IllegalStateException("Can't find jar file in " + targetDir);
		}
		return new File(targetDir, jarFiles[0]).getAbsolutePath();
	}
}
